import { Modal } from "antd";
import { io } from "socket.io-client";
import { useEffect, useState } from "react";

const TopModal = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const hideModal = () => {
    modalInfos.shift();
    setModalInfos([...modalInfos]);
    setIsModalOpen(false);
  };

  const handleOk = () => {
    hideModal();
  };

  const handleCancel = () => {
    hideModal();
  };

  const [modalInfos, setModalInfos] = useState([]);
  const [modalInfo, setModalInfo] = useState([]);
  const initSoketIo = () => {
    const socket = io("http://localhost:3002", {
      query: {
        id: "qwrlb3em22kk3",
        version: "0.0.1",
      },
    });
    socket.on("connect", () => {
      console.log("连接成功，id：" + socket.id);
      socket.on("disconnect", () => {
        console.log("客户端断开连接");
      });
      socket.on("modal", (data) => {
        modalInfos.push(data);
        setModalInfos([...modalInfos]);
      });
    });
  };

  useEffect(() => {
    initSoketIo();
  }, []);

  useEffect(() => {
    if (modalInfos.length > 0) {
      setModalInfo(modalInfos[0]);
      showModal();
    }
  }, [modalInfos]);

  return (
    <Modal
      maskClosable={false}
      centered={true}
      title={modalInfo.title}
      open={isModalOpen}
      onOk={handleOk}
      cancelButtonProps={{ style: { display: modalInfo.force ? "none" : "" } }}
      cancelText="关闭"
      okText={modalInfo.okBtnTxt ?? "确定"}
      onCancel={handleCancel}
    >
     
      <div dangerouslySetInnerHTML={{ __html: modalInfo.content }}></div>
    </Modal>
  );
};
export default TopModal;
